package com.tdcoding.chat.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.tdcoding.chat.action.common.ActionContext;
import com.tdcoding.chat.constants.ChatConstants;
import com.tdcoding.chat.constants.MainConstants;
import com.tdcoding.chat.dbase.DBForChat;
import com.tdcoding.chat.dbase.mapper.ChatMapper;
import com.tdcoding.chat.entities.ChannelInfo;
import com.tdcoding.chat.entities.ChatInfo;
import com.tdcoding.chat.entities.EmailInfo;
import com.tdcoding.chat.entities.NewsInfo;
import com.tdcoding.chat.entities.RequestInfo;
import com.tdcoding.chat.helper.FileHelper;
import com.tdcoding.chat.helper.Logger;
import com.tdcoding.chat.helper.StringHelper;
import com.tdcoding.chat.manager.ChatManager;
import com.tdcoding.chat.manager.DBManager;

import io.netty.channel.Channel;

public class ChatAction extends BaseAction{
	
	public void queryChatInfo(Channel channel,RequestInfo requestInfo){
		Logger.println(this, "queryChatInfo", requestInfo);
		Object[] parameters=requestInfo.getParameters();
		int chatState=Integer.parseInt(parameters[0].toString());
		SqlSession sqlSession=DBManager.getSqlSession();
		if (sqlSession==null) {
			return;
		}
		ChatMapper mapper=sqlSession.getMapper(ChatMapper.class);
		List<ChatInfo> chatInfos=mapper.queryChatInfo(requestInfo.getUserId(),chatState);
		if (chatInfos==null) {
			ActionContext.writeResponse(channel,requestInfo.getPacketId(),requestInfo.getMethod(),-1,"");
		}
		else{
			try {
				Thread.sleep(10000);
				Logger.println(this, "queryChatInfo~", channel.isActive(),channel.isOpen());
				ActionContext.writeResponse(channel,requestInfo.getPacketId(),requestInfo.getMethod(), 0, chatInfos);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 更新消息发生后的状态
	 * @param channel
	 * @param requestInfo
	 */
	public void updateChatInfo(Channel channel,RequestInfo requestInfo){
		Logger.println(this, "updateChatInfo", requestInfo);
		Object[] parameters=requestInfo.getParameters();
		int chatState=Integer.parseInt(parameters[0].toString());
		List<Object> packetIds=Arrays.asList(parameters[1]);
		String set="chatState="+chatState;
		for (Object packetId : packetIds) {
			String where="packetId='"+packetId+"'";
			int result=DBForChat.updateChatInfo(set, where);
		}
	}
	
	/**
	 * 全系统推送消息
	 * @param channel
	 * @param requestInfo
	 */
	@SuppressWarnings("unchecked")
	public void pushNews(Channel channel,RequestInfo requestInfo)  {
		Logger.println(this, "pushNews",requestInfo);
		String packetId=requestInfo.getPacketId();
		Object[] parameters=requestInfo.getParameters();
		ChatInfo chatInfo = getChatInfo(packetId,
				ChatConstants.CHAT_TYPE_NEWS_NOTICE,
				ChatConstants.CHAT_BODYTYPE_NEWS);
		chatInfo.setChatId(ChatConstants.CHAT_ADMINISTRATOR);
		chatInfo.setChatContent(parameters[0].toString());
		
		List<NewsInfo> newsInfos=((List<NewsInfo>) parameters[0]);
		
		ArrayList<ChannelInfo> lChannelInfos = ChatManager.getAllChannelInfos();
		for (NewsInfo newsInfo : newsInfos) {
			chatInfo.setChatContent(newsInfo.toString());
			for (ChannelInfo channelInfo : lChannelInfos) {
				chatInfo.setPacketId(StringHelper.packetId());
				chatInfo.setChatToId(channelInfo.getUserId());
				int result=DBForChat.addChatInfo(ChatConstants.MSG_SEND_SENDING,chatInfo);
				if (result==0&&channelInfo.getChatChannel()!=null
						&&channelInfo.getStatus()==MainConstants.USER_STATUS_ONLINE
						&&channelInfo.getChatChannel().isActive()
						) {
					ActionContext.handleResponse(channelInfo.getChatChannel(),chatInfo.getPacketId(),ChatConstants.MSG_RECEIVE, 0, chatInfo);
				} 
			}
		}
		ActionContext.writeResponse(channel,packetId,requestInfo.getMethod(), 0,"");
	}
	
	/**
	 * 全系统推送消息
	 * @param channel
	 * @param requestInfo
	 */
	@SuppressWarnings("unchecked")
	public void pushEmails(Channel channel,RequestInfo requestInfo)  {
		Logger.println(this, "pushEmails",requestInfo);
		String packetId=requestInfo.getPacketId();
		Object[] parameters=requestInfo.getParameters();
		ChatInfo chatInfo = getChatInfo(packetId,
				ChatConstants.CHAT_TYPE_EMAIL_NOTICE,
				ChatConstants.CHAT_BODYTYPE_EMAIL);
		chatInfo.setChatId(ChatConstants.CHAT_ADMINISTRATOR);
		
		List<EmailInfo> emailInfos=((List<EmailInfo>) parameters[0]);
		
		ArrayList<ChannelInfo> lChannelInfos = ChatManager.getAllChannelInfos();
		
		for (EmailInfo emailInfo : emailInfos) {
			chatInfo.setChatContent(emailInfo.toString());
			for (ChannelInfo channelInfo : lChannelInfos) {
				chatInfo.setPacketId(StringHelper.packetId());
				chatInfo.setChatToId(channelInfo.getUserId());
				int result=DBForChat.addChatInfo(ChatConstants.MSG_SEND_SENDING,chatInfo);
				if (result==0&&channelInfo.getChatChannel()!=null
						&&channelInfo.getStatus()==MainConstants.USER_STATUS_ONLINE
						&&channelInfo.getChatChannel().isActive()
						) {
					ActionContext.handleResponse(channelInfo.getChatChannel(),chatInfo.getPacketId(),ChatConstants.MSG_RECEIVE, 0, chatInfo);
				} 
			}
		}
		ActionContext.writeResponse(channel,packetId,requestInfo.getMethod(), 0,"");
	}
	
	/**
	 * 下载语音文件
	 * @param channel
	 * @param requestInfo
	 */
	public void downloadVoice(Channel channel,RequestInfo requestInfo)  {
		String packetId=requestInfo.getPacketId();
		String fileLink=(String) requestInfo.getParameters()[0];
		String fileName=fileLink.replace(MainConstants.SERVER_FILE_URL, "");
		String filePath=MainConstants.SERVER_FILE_PATH+File.separator+fileName;
		File voiceFile=new File(filePath);
		Logger.println(this, "downloadVoice", voiceFile.exists(),voiceFile.getAbsolutePath());
		if (voiceFile==null||!voiceFile.exists()) {
			ActionContext.writeResponse(channel,packetId,requestInfo.getMethod(), -1, "");
			return;
		}
		byte[] fileBytes=FileHelper.file2Bytes(voiceFile.getAbsolutePath());
		ActionContext.writeResponse(channel,packetId,requestInfo.getMethod(), 0,"",fileBytes);
	}
	
}
